﻿using System;
using System.Net;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.IO;
using FirstFloor.Documents;

namespace SampleBrowser.Common.IO
{
    /// <summary>
    /// Provides a sample implementation of decrypting package parts.
    /// </summary>
    public class SamplePackageDecrypter
        : IPackageDecrypter
    {
        /// <summary>
        /// Maps a request for given part to another part
        /// </summary>
        /// <param name="partUri">The part URI.</param>
        /// <returns>The mapped URI.</returns>
        /// <remarks>
        /// Part URI mapping allows a package to store encrypted parts in a another location.
        /// </remarks>
        public Uri MapPartUri(Uri partUri)
        {
            // Part URI mapping is useful if you want to be able to display an encrypted document in conventional XPS readers.
            // For instance: if page content is encrypted, you may want to leave a dummy page on the original page location and
            // move the encrypted page to another location. Use this method to map the requested part Uri to the location of the encrypted part.

            // This implementation assumes all .fpage content is encrypted and moved to a another location
            var fileName = partUri.GetFileName();
            var extension = Path.GetExtension(fileName);
            if (extension == ".fpage"){
                return new Uri(string.Format("/EncryptedPages/{0}", fileName));
            }
            
            return partUri;
        }

        /// <summary>
        /// Decrypts the specified part.
        /// </summary>
        /// <param name="partUri">The part URI.</param>
        /// <param name="stream">The stream.</param>
        /// <returns></returns>
        public Stream DecryptPart(Uri partUri, Stream stream)
        {
            if (partUri == null) {
                throw new ArgumentNullException("partUri");
            }
            if (stream == null) {
                throw new ArgumentNullException("stream");
            }

            // This implementation assumes .fpage content is encrypted
            var extension = Path.GetExtension(partUri.GetFileName());
            if (extension == ".fpage") {
                // TODO: add you custom decryption logic
                return stream;
            }
            return stream;
        }
    }
}
